/* Copyright 2008 Shawn C. Dodd

This file is part of TagFC.  TagFC is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

TagFC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with TagFC.  If not, see <http://www.gnu.org/licenses/>. */

class FetchPhotoJob {

	def startDelay = 5000l		// race conditions are bad
	def timeout = 120000l		// how often
	def group = "TagFC"

	// Put the entries from an ATOM feed into the SimpleEntry table.
	def donotexecute() {

		// TODO  database driven		
		File feedFile = new File("feed-flickr-group-cc.xml")
		File newName = new File("feed-flickr-group-cc.xml-ingested-${String.format('%tY%<tm%<td%<tH%<tM%<tS',new Date())}")
		def saveCount = 0

		// try to open the feed file
		if( !feedFile.exists() ) return
		def entr = new XmlSlurper().parse(feedFile)

		// insert all the entries into the database
		// TODO  we should check for duplicate entries
		entr.entry.each {
			// validation goes here
			def linkEnclosure=it.link.findAll{ it.@rel=="enclosure" }
			def linkLicense=it.link.findAll{ it.@rel=="license" }
			// TODO  gonna want a lot of error-checking logic here

			// TODO  make sure CC license allows commercial use

			// look for the thumbnail buried in the HTML content
			def contentHtml=it.content.findAll{ it.@type=="html" }
			def thumbMatch = contentHtml =~ /img.src.*(http.*_m.jpg)/

			// insert Entry into the DB
			def simple = new SimpleEntry()
			simple.uri = it.id
			simple.namespace = "flickr"
			simple.fullImageURL = linkEnclosure.@href
			simple.thumbnailURL = thumbMatch[0][1]	// want the first one
			simple.tags = ""
			simple.markupFragment = ""		// TODO  whole string
			def saved = simple.save()
			if(!saved) println "[Ingest] Oops! Couldn't save entry."
			else {
				// now insert Piece
				def piece = new Piece()
				piece.simpleEntry = simple
				piece.state = "unproc"
				if( piece.save() ) saveCount++
			}
		}

		// summarize results
		println "${String.format('%tF %<tT',new Date())} [Ingest] Added ${saveCount} SimpleEntry objects"

		// rename the file so we won't see it next time
		def success = feedFile.renameTo(newName)
		if( !success ) 
			println "Oops! Couldn't rename feed file."
	}

}
